import yaml
from easydict import EasyDict as edict


class YamlParser(edict):
    def __init__(self, configs=None, config_file=None):
        if configs is None:
            configs = {}
        if config_file is not None:
            with open(config_file, 'r') as f:
                yaml_ = yaml.load(f.read(), Loader=yaml.FullLoader)
            configs.update(yaml_)
        super(YamlParser, self).__init__(configs)
    
    def merge_from_file(self, config_file):
        with open(config_file, 'r') as f:
            yaml_ = yaml.load(f.read(), Loader=yaml.FullLoader)
        self.update(yaml_)

    def merge_from_dict(self, configs):
        self.update(configs)


def get_config(config_path):
    cfg = YamlParser(config_file=config_path)
    return cfg


def get_config_subs(config_path):
    cfg = YamlParser(config_file=config_path)
    if 'MODEL' in cfg and isinstance(cfg.MODEL, str):
        cfg.MODEL = YamlParser(config_file=cfg.MODEL)
    if 'DATA' in cfg and isinstance(cfg.DATA, str):
        cfg.DATA = YamlParser(config_file=cfg.DATA)
    
    # overwrite basics
    if 'BG0' in cfg:
        cfg.DATA.BG0 = cfg.BG0
    if 'DATA_ROOT' in cfg and cfg.DATA_ROOT:
        cfg.DATA.DATA_ROOT = cfg.DATA_ROOT
    
    return cfg
